#include <iostream>
#include <thread>
#include <cstring>
#include <arpa/inet.h>
#include <unistd.h>

//让chatgpt写的基于多线程的UDP循环发送接收代码，测试过OK，编译命令是g++ -o udp_multithread udp_multithread.cpp -lpthread

#define LOCAL_PORT 8888 // 本地端口号
#define BUFFER_SIZE 1024 // 缓冲区大小
#define SEND_INTERVAL 3 // 发送间隔（秒）

void receiverThread() {
    // 创建 UDP 套接字
    int sockfd;
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        std::cerr << "Error creating socket" << std::endl;
        return;
    }

    // 准备本地地址
    struct sockaddr_in localAddr;
    memset(&localAddr, 0, sizeof(localAddr));
    localAddr.sin_family = AF_INET;
    localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    localAddr.sin_port = htons(LOCAL_PORT);

    // 绑定本地地址到套接字
    if (bind(sockfd, (struct sockaddr*)&localAddr, sizeof(localAddr)) < 0) {
        std::cerr << "Bind failed" << std::endl;
        close(sockfd);
        return;
    }

    // 接收数据并打印
    char buffer[BUFFER_SIZE];
    struct sockaddr_in senderAddr;
    socklen_t senderAddrLen = sizeof(senderAddr);
    while (true) {
        ssize_t recv_len = recvfrom(sockfd, buffer, BUFFER_SIZE, 0, (struct sockaddr*)&senderAddr, &senderAddrLen);
        if (recv_len < 0) {
            std::cerr << "Receive error" << std::endl;
            continue;
        }
        buffer[recv_len] = '\0';
        std::cout << "Received message from " << inet_ntoa(senderAddr.sin_addr) << ": " << buffer << std::endl;
    }

    // 关闭套接字
    close(sockfd);
}

void senderThread() {
    // 创建 UDP 套接字
    int sockfd;
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        std::cerr << "Error creating socket" << std::endl;
        return;
    }

    // 准备目标地址
    struct sockaddr_in targetAddr;
    memset(&targetAddr, 0, sizeof(targetAddr));
    targetAddr.sin_family = AF_INET;
    targetAddr.sin_port = htons(LOCAL_PORT); // 目标端口与本地端口相同
    if (inet_aton("127.0.0.1", &targetAddr.sin_addr) == 0) {
        std::cerr << "Invalid address" << std::endl;
        close(sockfd);
        return;
    }

    // 发送数据
    const char* message = "Hello from sender!";
    while (true) {
        ssize_t send_len = sendto(sockfd, message, strlen(message), 0, (struct sockaddr*)&targetAddr, sizeof(targetAddr));
        if (send_len < 0) {
            std::cerr << "Send error" << std::endl;
        }
        sleep(SEND_INTERVAL); // 等待一段时间再发送
    }

    // 关闭套接字
    close(sockfd);
}

int main() {
    // 创建接收线程
    std::thread receiver(receiverThread);

    // 创建发送线程
    std::thread sender(senderThread);

    // 等待线程结束
    receiver.join();
    sender.join();

    return 0;
}
